//
//  NSObject+TYJSONSerialization.m
//  TYFoundationUtils
//
//  Created by 郭艺伟 on 2019/2/27.
//  Copyright © 2019年 厦门IOS开发团队. All rights reserved.
//

#import "NSObject+TYJSONSerialization.h"

@implementation NSObject (TYJSONSerialization)
- (BOOL)ty_isValidJSONObject {
    return [NSJSONSerialization isValidJSONObject:self];
}

- (NSString *)ty_jsonRepresentation {
    return [self ty_jsonRepresentationWithError:nil];
}

- (NSString *)ty_jsonRepresentationWithError:(NSError * __autoreleasing *)error {
    return [self ty_jsonRepresentationWithOptions:NSJSONWritingPrettyPrinted error:error];
}

- (NSString *)ty_jsonRepresentationWithOptions:(NSJSONWritingOptions)options error:(NSError * __autoreleasing *)error {
    if ([self ty_isValidJSONObject]) {
        NSError *errorT = nil;
        NSData *data = [NSJSONSerialization dataWithJSONObject:self options:options error:&errorT];
        if (errorT) {
            if (error) {
                *error = errorT;
            }
            return nil;
        }
        NSString *strJson = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        
        if (!strJson) {
            return nil;
        }
        
        return strJson;
    }
    return nil;
}
@end
